package com.xmut.web;

import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.databean.SysUserDataBean;
import com.sirdc.modules.sys.entity.SysLogin;
import com.sirdc.modules.sys.service.SysUserService;
import com.sirdc.modules.sys.util.SysUserUtils;
import com.sirdc.modules.sys.util.UserUtils;
import com.sirdc.modules.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 */
@Controller
@RequestMapping("/pass/user")
public class FrontUserController extends JsonBaseController{

    @Autowired
    private SysUserService sysUserService;

    @Override
    protected String getView(String view) {
        return "/front/" + view;
    }

    /**
     * 返回个人中心页面
     * @param model
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public String showRegisterPage(Model model) {

        SysUserDataBean datebean = sysUserService.getUserDataBeanById(SysUserUtils.getUserId());
        model.addAttribute("datebean", datebean);


        return getView("user");
    }

    /**
     * 修改基本信息
     * @param datebean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Message update(@ModelAttribute SysUserDataBean datebean) {
        datebean.setUserId(SysUserUtils.getUserId());
        sysUserService.updateUserLogin(datebean);
        return coverMessage("200");
    }

    /**
     * 修改密码
     * @param databean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/password/edit", method = RequestMethod.POST)
    public Message changePass(@ModelAttribute SysUserDataBean databean) {
        if (StringUtils.isEmpty(databean.getPassword()) || StringUtils.isEmpty(databean.getOldPassword())) {
            return coverMessage("500", "请输入完整的信息");
        }
        String userId = UserUtils.getUserId();
        SysLogin login = sysUserService.getSysLoginById(userId);
        String encryptPass = sysUserService.getEncryPass(databean.getOldPassword(), login.getSaltKey());
        if(login.getPassword().equals(encryptPass)) {
            databean.setUserId(userId);
            sysUserService.updatePassword(databean);
            return coverMessage("200");
        }
        return coverMessage("500", "对不起，您当前输入的旧密码有误");
    }



}
